package com.xplay.xpocker.interceptor;

import com.xplay.xpocker.config.ResultFul;
import com.xplay.xpocker.entity.system.SysUser;
import com.xplay.xpocker.exception.StatusCodeEnum;
import com.xplay.xpocker.util.Assertion;
import com.xplay.xpocker.util.JacksonStringUtil;
import com.xplay.xpocker.util.JwtUtils;
import com.xplay.xpocker.util.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author wanjie
 * @date 2021/3/22 15:22
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String tokenStr = request.getHeader(JwtUtils.TOKEN_HEADER);
            Assertion.isTrue(null == tokenStr || tokenStr.equals(""), "找不到用户认证信息");
            Assertion.isTrue(!JwtUtils.validateToken(tokenStr), "token认证失败");
            Claims claims = JwtUtils.getAllClaimsFromToken(tokenStr);
            UserThreadLocal.setUser(new SysUser(claims.getId()));
            // 注意  这里ajax请求会带上opTIOS请求  此请求为认证
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "86400");
            response.setHeader("Access-Control-Allow-Headers", "*");
            // 如果是OPTIONS则结束请求
            if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
                response.setStatus(HttpStatus.NO_CONTENT.value());
                return false;
            }
            return true;
        } catch (Exception e) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,OPTIONS");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            PrintWriter responseWriter = response.getWriter();
            responseWriter.write(Objects.requireNonNull(JacksonStringUtil.objectToString(ResultFul.init(StatusCodeEnum.UNAUTHORIZED.getCode(),StatusCodeEnum.UNAUTHORIZED.getDesc()), false)));
            responseWriter.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeUser();
    }
}
